﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Shapes;
using Microsoft.Phone.Controls;
using System.IO;
using System.Xml.Linq;
using System.Collections.ObjectModel;
using System.Windows.Media.Imaging;

namespace BTLon_Develop_Mobile
{
    public partial class MainPage : PhoneApplicationPage
    {
        // Constructor
        
        public MainPage()
        {
            InitializeComponent();

            
            //
        }


        public void MakeSomeHTTPCall()
        {

            var request = (HttpWebRequest)WebRequest.Create("http://free.worldweatheronline.com/feed/weather.ashx?key=bed6524371124406111310&q=" + txtLocation.Text + "&num_of_days=5&format=xml"); //tao 1 request
            request.Method = "GET"; // phuong thuc request la GET
            request.BeginGetResponse(new AsyncCallback(GetSomeResponse), request); // Bat dau nhan du lieu phan hoi tu server

        }
       
        private void GetSomeResponse(IAsyncResult MyResultAsync)
        {

            // khai bao doi tuong de luu lieu
            Weather[] weatherForecast = new Weather[6];
            Weather weathercurrent = new Weather();

            
            HttpWebRequest request = (HttpWebRequest)MyResultAsync.AsyncState;
            try
            {
                HttpWebResponse response = (HttpWebResponse)request.EndGetResponse(MyResultAsync);
                if (response.StatusCode == HttpStatusCode.OK && response.ContentLength > 0)
                {
                    using (StreamReader sr = new StreamReader(response.GetResponseStream()))
                    {

                        XDocument doc = XDocument.Load(sr);  // load xml nhận đc vào XDocument
                    
                        weathercurrent.LocationName    = doc.Root.Element("request").Element("query").Value;    // luu ten cua thanh pho
    
                        weathercurrent.date = doc.Root.Element("current_condition").Element("observation_time").Value;  // thoi gian cap nhap moi nhat trong ngay` hien tai
                        weathercurrent.TempC = doc.Root.Element("current_condition").Element("temp_C").Value;           // Nhiet do cua ngay hien tai
                        weathercurrent.ImgSource = doc.Root.Element("current_condition").Element("weatherIconUrl").Value.Trim();    //Icon cua ngay hien tai
                    
                        
                        
                        // doan nay` thi` tu du lieu tra ve tu server minh tach du lieu rieng cho tung ngay`
                        // trong day co du lieu cua 5 ngay lien tiep ke tu` ngay` hien tai  => Muon hien thi bh ngay` thi tuy moi nguoi`
                        // de lay du lieu. cua tung` ngay` moi nguoi` lam theo cu phap nhu sau
                        // vd lay' du lieu cua ngay hom nay. va` hien thi ra 1 textbox thi chung ta lam nhu sau :)
                        
                        // textblock.text = weatherForecast[0].TempC    => Vd la nhiet do min 25*C
                        // textblock.text = weatherForecast[0].date    => Vd la  ngay hom nay la ngay` 25-4
                        // textblock.text = weatherForecast[0].TempCMax    => Vd la  nhiet do max la 50*C
                        // textblock.text = weatherForecast[0].Wind_Condition    => Vd la  toc do. gio' la 100K/h
                        // con` cai ImgSource thi` la` duong link vd nhu http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0002_sunny_intervals.png
                        // khi in ra XAML cac ban. chi can` cho cai' truong` source = "<duong link o tren>"  la no se in ra anh thoi :). don gian :)

                        // tuong tu: voi cac ngay` tiep theo cac ban cun lay' du lieu nhu the' nhung cai' chi? so mang phai tang nen :).
                        // vd
                        // textblock.text = weatherForecast[1].TempC
                        // va roi chu' the la in ra thoi :)

                        // to da~ xu ly du lieu tho thanh` du lieu. chuan roi :). moi nguoi` chi? viec. goi. doi tuong. ve cac' thuoc tinh ra la xong thoi :)
                        
                        var data = (from query in doc.Root.Descendants("weather")
                                   select new Weather
                                   {

                                        
                                        date = (string)query.Element("date").Value,
                                        TempC = (string)query.Element("tempMinC").Value,
                                        TempCMax = (string)query.Element("tempMaxC").Value,
                                        Wind_Condition = (string)query.Element("windspeedKmph").Value,
                                        ImgSource = (string)query.Element("weatherIconUrl").Value.Trim(),

                                   });
                        int i = 0;
                        foreach (Weather stockQuote in data)
                        {

                            weatherForecast[i] = stockQuote;
                            i++;

                        }
                       
                    }
                }
            }
            catch (WebException e)
            {
                if (e.Status == WebExceptionStatus.RequestCanceled)
                    Deployment.Current.Dispatcher.BeginInvoke(() =>
                    {

                        MessageBox.Show("Yêu cầu kết nối bị gián đoạn >\"<");

                    });
                else
                {
                    using (HttpWebResponse response = (HttpWebResponse)e.Response)
                    {
                        Deployment.Current.Dispatcher.BeginInvoke(() =>
                        {
                            MessageBox.Show("Lỗi http: " + response.StatusCode.ToString());

                        });
                    }
                }
            }
            finally
            {
               
            }
        }

        private void btnSearch_Click(object sender, RoutedEventArgs e)
        {
            if (!string.IsNullOrWhiteSpace(txtLocation.Text))
            {
                MakeSomeHTTPCall();
            }
        }
    }
}